package com.config;

import com.pojo.User;
import com.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义UserRealm  extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("执行了->授权doGetAuthorizationInfo");

        //拿到当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        //用户授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //伪造数据     数据库中取
        String name="root";
        String password="123456";

        System.out.println("执行了->认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken=(UsernamePasswordToken)authenticationToken;

        User user = userService.findUserByName(userToken.getUsername());
        System.out.println("user--->"+user);

        //用户名不存在
        if (user==null)
            return null;
//        if (!userToken.getUsername().equals(name)){
//            return null;  //抛出异常
//        }


        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);


        //密码认证  Shiro做                   传递用户
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
